package br.com.controller.converter;


import java.util.Map;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import br.com.model.entity.BaseEntity;

/**
 * Converter para objetos no componente SelectOneMenu, desenvolvida por Rafael Ponte (http://www.rponte.com.br)
 * @author Lindoélio Lázaro
 */

public class SimpleEntityConverter implements Converter {
    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
        if (value != null) {
            return this.getAttributesFrom(component).get(value);
        }
        return null;
    }
  
    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {  
        if (object != null && !(object).equals("")) {
            BaseEntity entity = (BaseEntity) object;
            this.addAttribute(component, entity);
            Long id = entity.getPk();
            if (id != null) {
                return String.valueOf(id);
            }
        }
        return (String) object;
    }

    protected void addAttribute(UIComponent component, BaseEntity o) {
        String key = o.getPk().toString();
        this.getAttributesFrom(component).put(key, o);
    }

    protected Map<String, Object> getAttributesFrom(UIComponent component) {
        return component.getAttributes();
    }
}
